<template>
  <iframe
    v-if="iframeShow"
    id="ddAuthCode"
    ref="dingdingIframe"
    name="ddAuthCode"
    frameborder="0"
    hspace="0"
    vspace="0"
    :src="DDLoginUrl"
    scrolling="no"
    style="display: none;"
    @load="onload"
  />
</template>
<script>
import permissionApi from '@/api/bms/permission'
import { sleep } from '@/utils'
import storeUtil from '@/utils/store'

export default {
  name: 'DingQr',
  props: {
    isDDloginType: {
      type: String,
      default() {
        return ''
      }
    },
    // 登录成功回跳地址
    redirect: {
      type: String,
      default() {
        return '/'
      }
    }
  },
  data() {
    return {
      iframeShow: false,
      isHanndleMessage: false,
      DDLoginUrl: '',
      qrcodeUrl: '',
      DDLogining: ''
    }
  },
  watch: {
    // 判断登录类型
    isDDloginType(val) {
      if (val === 'ding') {
        const vm = this
        vm.isHanndleMessage = false
        const qrcodeUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${process.env.VUE_APP_APP_ID}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${process.env.VUE_APP_DDAPI_ROOT}`
        const qrcodeUrlEncode = encodeURIComponent(qrcodeUrl)
        vm.qrcodeUrl = qrcodeUrl
        window.DDLogin({
          id: 'loginContainer',
          goto: qrcodeUrlEncode,
          style: 'border:none;background-color:#FFFFFF;',
          width: '285',
          height: '300'
        })
        if (typeof window.addEventListener !== 'undefined') {
          window.addEventListener('message', vm.hanndleMessage, false)
        } else if (typeof window.attachEvent !== 'undefined') {
          window.attachEvent('onmessage', vm.hanndleMessage)
        }
      }
    }
  },
  methods: {
    onload(e) {
      try {
        const dingdingIframe = this.$refs.dingdingIframe
        if (!dingdingIframe.contentDocument) {
          this.DDLogining()
        }
      } catch (err) {
        console.log(err)
        // TODO
      }
    },
    async hanndleMessage(event) {
      const vm = this
      const origin = event.origin
      if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
        const loginTmpCode = event.data // 拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        if (vm.isHanndleMessage && loginTmpCode) {
          return
        }
        vm.isHanndleMessage = true
        storeUtil.setStore('scanLogin', 'onlyScan')
        vm.DDLogining = this.$Message.loading({
          content: '正在登录，请稍等...',
          duration: 0
        })
        vm.iframeShow = true
        vm.DDLoginUrl = vm.qrcodeUrl + '&loginTmpCode=' + loginTmpCode
        await sleep(1000)
        vm.getDDAuthCode()
      }
    },
    getQueryStringArgs(search) {
      // 取得查询字符串并去掉开头的问号
      const qs = (search.length > 0 ? search.substring(1) : '')
      // 保存数据的对象
      const args = {}
      // 取得每一项
      const items = qs.length ? qs.split('&') : []
      let item = null
      let name = null
      let value = null
      const len = items.length
      // 逐个将每一项添加到args对象中
      for (let i = 0; i < len; i++) {
        item = items[i].split('=')
        name = decodeURIComponent(item[0])
        value = decodeURIComponent(item[1])
        if (name.length) {
          args[name] = value
        }
      }
      return args
    },
    async fnDDGetUserToken(account, code) {
      const vm = this
      try {
        const result = await permissionApi.dingtalkToken({
          account: account,
          code: code
        }).then(this.serviceUtil.filterBmsBackendData)
        vm.DDLogining()
        // 清除顶部菜单路由的opition
        window.zhnxSSO.saveRefreshToken(result.refreshToken).then(result => console.log(result.data)).catch(error => console.log(error))
        this.$store.dispatch('saveBmsMsg', result)
        this.$router.push({ path: this.redirect || '/' }).catch(() => {})
      } catch (err) {
        this.showError(err)
        vm.DDLogining()
      }
    },
    fnClearSession() {
      storeUtil.clearAllStore()
    },
    async getDDAuthCode() {
      let authCode = ''
      let search = ''
      // IE浏览器
      if (document.frames) {
        search = document.frames['ddAuthCode'].location.search
      } else {
        search = document.getElementById('ddAuthCode').contentWindow.location.search
      }
      authCode = this.getQueryStringArgs(search).code
      storeUtil.setStore('scanLogin', 'requestUserInfo')
      try {
        const result = await permissionApi.dingtalkAuth({
          code: authCode
        }).then(this.serviceUtil.filterBmsBackendData)
        this.fnDDGetUserToken(result.mobile, authCode)
      } catch (err) {
        this.DDLogining()
        this.showError(err)
      }
    }
  }
}

</script>
